from board import Board
from config import GameConfig
from color_type import ColorType
from tile_model import TileModel


class BoardController:
    __instance = None

    @staticmethod
    def getInstance():
        if BoardController.__instance == None:
            BoardController.__instance = BoardController()
        return BoardController.__instance

    def __init__(self):
        self._main_scene = None
        self._board = None
        self._tile_arr = [[TileModel(x, y)
                           for x in range(GameConfig.BOARD_TILE_WIDTH)]for y in range(GameConfig.BOARD_TILE_HEIGHT)]

    def init(self, main_scene):
        self._main_scene = main_scene

        self._board = Board(
            GameConfig.BOARD_TILE_WIDTH,
            GameConfig.BOARD_TILE_HEIGHT,
            GameConfig.TILE_SIZE,
            GameConfig.TILE_INTERVAL
        )
        main_scene.add(self._board)

    def render(self, tile_model=[]):
        self._board.render(tile_model)

    def get_tile(self, x, y):
        if x < 0 or x >= GameConfig.BOARD_TILE_WIDTH:
            return None
        if y < 0 or y >= GameConfig.BOARD_TILE_HEIGHT:
            return None
        return self._tile_arr[y][x]

    def check_collision(self, tile_model):
        for model in tile_model:
            if model.y < 0:
                return False
            tile = self.get_tile(model.x, model.y)
            if tile and tile.color != ColorType.Empty:
                return False
        return True

    def check_valid(self, tile_model):
        for model in tile_model:
            if model.x < 0 or model.x >= GameConfig.BOARD_TILE_WIDTH:
                return False
            tile = self.get_tile(model.x, model.y)
            if tile and tile.color != ColorType.Empty:
                return False
        return True

    def merge_tile(self, tile_model):
        for model in tile_model:
            tile = self.get_tile(model.x, model.y)
            if tile:
                tile.color = model.color

    def get_tile_model(self):
        result = []
        for line in self._tile_arr:
            for tile in line:
                if tile.color != ColorType.Empty:
                    result.append(tile)
        return result
